import hashlib
from django.http import HttpResponse
from django.shortcuts import render
from blog.models import User

# Create your views here.
def login_page(request):
    if request.method == 'GET':
        if request.session.get('username') and request.session.get('uuid'):
            return HttpResponse('已登录')
        elif request.COOKIES.get('username') and request.CooKIES.get('uuid'):
            request.session['username'] = request.cooKIES.get('username')
            request.session['uuid'] = request.CooKIES.get('uuid')
            return HttpResponse('已登录')
        return render(request,'login.html')

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        print(f'用户名：{username}')
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            return HttpResponse('用户名不存在')

        md = hashlib.md5()
        md.update(password.encode())
        password = md.hexdigest()
        if password != user.password:
            return HttpResponse('密码错误')

        request.session['username'] = username
        request.session['uuid']=user.id

        resp = HttpResponse('登陆成功')
        if 'remmben' in request.POST:
            resp.set_cookie('username',username,3600 * 24 * 3)
            resp.set_cookie('uuid',user.id,3600 * 24 * 3)

        return resp



def reg_view(request):
    if request.method == 'GET':
        return render(request,'register.html')
    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        old_users = User.objects.filter(username=username)
        if old_users:
            return HttpResponse('用户名已注册')
        # 3，插入数据[明文处理密码］
        m = hashlib.md5()
        m.update(password.encode())
        password = m.hexdigest()
        User.objects.create(username=username, password=password)

        # request.session['username'] = username
        # request.session['uid']=
        # return HttpResponse('注册成功')
        request.session['username'] = username
        return HttpResponse('注册成功')

    def index(request):
        return render(request, 'index.html')

    def logout_view(request):
        logout(request)
        return HttpResponseRedirect('/blog/index')
        # return HttpResponse('退出成功')